<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.userName" clearable class="filter-item" style="width: 200px;" placeholder="请输入昵称" />
      <el-input v-model="listQuery.cardNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入会员卡号" />
      <el-input v-model="listQuery.phone" clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号" />
      <el-button
        v-permission="['promote:usercard:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="handleExport"
      >导出</el-button>
      <div class="filter-item">{{ '当前会员总额: ' + balanceSum / 100.0 }}</div>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <div class="filter-item">{{ '会员总人数: '+count }}</div>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="nickname" align="center" label="用户名称"/>
      <el-table-column prop="phone" align="center" label="手机号"/>
      <el-table-column align="center" label="性别" prop="gender">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.gender | genderDicFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="卡号" prop="cardNo">
        <template slot-scope="scope">
          <span>{{ scope.row.cardNo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="余额" prop="balance">
        <template slot-scope="scope">
          <el-col>{{ (scope.row.balance/100).toFixed(2) }}</el-col>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            v-permission="['system:user:update']"
            type="primary"
            width="100"
            size="mini"
            @click="handleCharge(scope.row)"
          >充值记录</el-button>
          <el-button
            v-permission="['system:user:update']"
            type="primary"
            size="mini"
            @click="handlePay(scope.row)"
          >消费记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="编号" prop="id">
          <el-input v-model="dataForm.id" disabled />
        </el-form-item>
        <el-form-item label="绑定用户" prop="userId">
          <el-input v-model="dataForm.userId" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="卡号" prop="cardNo">
          <el-input v-model="dataForm.cardNo" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="卡密" prop="cardSecret">
          <el-input v-model="dataForm.cardSecret" clearable placeholder="" disabled/>
        </el-form-item>
        <el-form-item label="卡金额" prop="money">
          <el-input v-model="dataForm.money" clearable placeholder="" disabled/>
        </el-form-item>
        <!--<el-form-item label="有效开始时间" prop="gmtStart">
          <el-input v-model="dataForm.gmtStart" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="有效截止时间" prop="gmtEnd">
          <el-input v-model="dataForm.gmtEnd" clearable placeholder=""/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">绑定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="importDialogVisible"
      title="导入用户卡"
      width="35%"
    >
      <el-dialog
        :visible.sync="innerImportDialogVisible"
        width="30%"
        title="系统提示"
        append-to-body>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="4">总计:{{ allResult }}</el-col>
          <el-col :span="4">成功:{{ successResult }}</el-col>
          <el-col :span="4">失败:{{ errResult }}</el-col>
        </el-row>
        <el-row v-if="errResult && errResult > 0">
          <el-col :span="4"><el-button type="primary" @click="handleErrResult">导出错误信息</el-button></el-col>
        </el-row>
      </el-dialog>
      <div style="border:none;">
        <el-button icon="el-icon-document-copy" type="primary" size="small" style="margin-left: 15px;" @click="checkFile">选择文件</el-button>
        <span>{{ fileName }}</span>
        <el-input id="fileinput" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" style="display: none;" @change="checkFileSure"/>
        <el-link type="primary" href="../../static/excel/template.xls" target="_blank">下载模板</el-link>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="(!fileName)" :loading="importOptLoading" type="primary" @click="importExcel">导 入</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="logTextMap[logDialogType]" :visible.sync="logTableVisible">
      <el-table
        v-loading="logListLoading"
        :data="logList"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        style="white-space: pre-line"
      >
        <el-table-column property="description" label="描述" width="150">
          <template slot-scope="scope">
            <el-col v-if="logDialogType == 'charge'">{{ scope.row.description }}</el-col>
            <el-col v-if="logDialogType == 'pay'">{{ scope.row.description }}</el-col>
          </template>
        </el-table-column>
        <el-table-column align="center" label="时间">
          <template slot-scope="scope">{{ scope.row.gmtCreate | formatGmt }}</template>
        </el-table-column>
        <el-table-column align="center" label="余额">
          <template slot-scope="scope">{{ (scope.row.balance/100).toFixed(2) }}</template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="logListTotal>0"
        :total="logListTotal"
        :page.sync="listLogQuery.pageNo"
        :limit.sync="listLogQuery.limit"
        @pagination="getLogList"
      />
    </el-dialog>
    <!-- 截至汇总统计 -->
    <el-dialog :title="'截至 数据汇总'" :visible.sync="sumTableVisible">
      <el-table
        v-loading="logListLoading"
        :data="sumMap"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        style="white-space: pre-line"
      >
        <el-table-column align="center" label="余额汇总" prop="balanceSum">
          <template slot-scope="scope">{{ (scope.row.balanceSum/100).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column align="center" label="会员总数" prop="count"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { list, save, del, update, active, importExcel, exportToExcel, monthSummary } from '@/api/usercard'
import { chargeLog, payLog } from '@/api/user'
import { formatDateAndTime } from '@/filters'
import Pagination from '@/components/Pagination' // Secondary pacge based on el-pagination
const genderDic = [{ value: 1, name: '女' }, { value: 2, name: '男' }, { value: '', name: '全部' }]
export default {
  name: 'UserCard',
  components: { Pagination },
  filters: {
    formatStatus(status) {
      if (status === 0) {
        return '冻结'
      } else if (status === 1) {
        return '未使用'
      } else if (status === 2) {
        return '已使用'
      } else if (status < 0) {
        return '已过期'
      } else {
        return '错误状态'
      }
    },
    genderDicFilter(code) {
      if (code === 1 || code === 2) {
        return genderDic[code - 1].name
      } else {
        return '未知性别'
      }
    },
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTime(time)
    }
  },
  data() {
    return {
      statusMap: [{ value: 0, name: '禁用' }, { value: 1, name: '未使用' }, { value: 2, name: '已使用' }],
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 10,
        status: undefined,
        cardNo: ''
      },
      sumMonthQuery: {
        gmtMouth: undefined
      },
      options: [],
      errList: [],
      dataForm: {
        id: undefined,
        userId: undefined,
        cardNo: undefined,
        description: undefined,
        cardSecret: 0,
        money: 0,
        status: 1
      },
      activationCard: false,
      sumMap: undefined,
      dialogFormVisible: false,
      logTableVisible: false,
      balanceSum: 0,
      count: 0,
      sumTableVisible: false,
      logList: [],
      logListTotal: 0,
      dialogStatus: '',
      logDialogType: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {},
      importDialogVisible: false,
      innerImportDialogVisible: false,
      successResult: 0,
      errResult: 0,
      allResult: 0,
      importOptLoading: false,
      logListLoading: false,
      listLogQuery: {
        pageNo: 1,
        limit: 20,
        userId: undefined
      },
      logTextMap: {
        charge: '充值记录',
        pay: '消费记录'
      },
      uploadForm: new FormData(),
      fileName: '',
      file: ''
    }
  },
  created() {
    this.getList()
    this.monthSummary()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
        // 为过期会员卡赋负值
          response.data.data.items.forEach(item => {
            var now = new Date()
            if (item.gmtEnd < now) {
              item.status = -1
            }
            item.money = item.money / 100
          })
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 2 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '充值成功'
          })
          this.getList()
        })
        .catch(() => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.refreshOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      save(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      update(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '绑定成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleRead(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.refreshOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleImport() {
      this.importDialogVisible = true
      this.$set(this, 'fileName', '')
      this.errList = []
    },
    checkFile() {
      document.querySelector('#fileinput').click()
    },
    checkFileSure(val) {
      const file = document.querySelector('#fileinput').files[0]
      this.file = file
      this.fileName = file.name
    },
    importExcel() {
      this.errList = []
      this.importOptLoading = true
      importExcel(this.file)
        .then(response => {
          const result = response.data
          this.errList = response.data.failResult
          var type = result.errno === 200 ? 'success' : 'error'
          if (result && result.data && result.data !== '') {
            this.successResult = result.data.success
            this.errResult = result.data.fail
            this.allResult = result.data.total
            this.errList = (result.data.fail === 0 ? [] : result.data.failResult)
            this.innerImportDialogVisible = true
          } else {
            this.$notify({
              title: '成功',
              type: type,
              message: response.data.errmsg
            })
          }
          this.importOptLoading = false
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
          this.importOptLoading = false
          this.errList = []
        })
    },
    handleErrResult() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '用户名',
          '手机号',
          '卡号',
          '卡名称',
          '失败原因'
        ]
        const filterVal = [
          'userName',
          'phone',
          'cardNo',
          'cardName',
          'cause'
        ]
        excel.export_json_to_excel2(tHeader, this.errList, filterVal, '导入失败信息汇总')
      })
    },
    handleCharge(row) {
      this.logTableVisible = true
      this.logDialogType = 'charge'
      this.listLogQuery.userId = row.userId
      this.getLogList()
    },
    handlePay(row) {
      this.logTableVisible = true
      this.logDialogType = 'pay'
      this.listLogQuery.userId = row.userId
      this.getLogList()
    },
    monthSummary() {
      monthSummary(this.sumMonthQuery)
        .then(response => {
          this.balanceSum = response.data.data.balanceSum
          this.count = response.data.data.count
        })
        .catch(response => {

        })
    },
    formatGmt(time) {
      if (time == null || time === '') {
        return ''
      }
      return formatDateAndTime(time)
    },
    getLogList() {
      if (this.logDialogType === 'charge') {
        this.chargeLog(this.listLogQuery)
      } else {
        this.payLog(this.listLogQuery)
      }
    },
    chargeLog(userId) {
      chargeLog(userId)
        .then(response => {
          this.logList = response.data.data.items
          this.logListTotal = response.data.data.total
          this.logListLoading = false
        })
        .catch(response => {
          this.logList = []
          this.logListTotal = 0
          this.logListLoading = false
        })
    },
    payLog(userId) {
      payLog(userId)
        .then(response => {
          this.logList = response.data.data.items
          this.logListTotal = response.data.data.total
          this.logListLoading = false
        })
        .catch(response => {
          this.logList = []
          this.logListTotal = 0
          this.logListLoading = false
        })
    },
    handleExport() {
      exportToExcel(this.listQuery.cardNo, this.listQuery.userName, this.listQuery.phone)
    }
  }
}
</script>
